
<?php

require 'config_inc.php';
require 'dal_common.php';
require 'dal_account.php';
require 'dal_session.php';
require 'api_common.php';

$t_args = get_params(Array(
	'app' => '+app',
	'os' => '+os',
	'username' => '-username',
	'password' => '-any',
	'device' => '-device'
));
if ($t_args == null) {
	echo 'ERROR=INVALID_PARAMETER;';
	return;
}

if ($t_args['username'] == '') {
	if ($t_args['device'] == '') {
		echo '[' . __LINE__ . ']';
		echo 'ERROR=INVALID_PARAMETER;';
		return;
	}
	
	$t_uinfo = dal_account_get_userinfo_by_device($t_args['device']);
	if ($t_uinfo == NULL) {
		if (!dal_account_register_device($t_args['device'])) {
			echo 'ERROR=SYSTEM_ERROR';
			return;
		}
	}
	$t_args['username'] = '@' . $t_args['device'];
	$t_args['password'] = '';
} else {
	if ($t_args['password'] == '') {
		echo '[' . __LINE__ . ']';
		echo 'ERROR=INVALID_PARAMETER';
		return;
	}
}

$t_userid = dal_account_auth($t_args['username'], $t_args['password']);
if ($t_userid < 0) {
	echo 'ERROR=AUTH_FAILED';
	return;
}

$t_token = gen_token();
if (!dal_session_add($t_token, 10000000, $t_userid, $t_args['device'], $t_args['app'], $t_args['os'], get_request_ip())) {
	echo 'ERROR=AUTH_FAILED';
	return;
}

echo 'ERROR=0;' . $t_token;
?>
